<?php

// check user login
session_start();
if (isset($_SESSION["user"]) && !empty($_SESSION["user"])) {
//echo $_SESSION["user"];




class Main_interface extends CI_Controller {

	public function __construct() {
            parent::__construct(); 

            $this->load->helper(array('form','url'));
            $this->load->library('form_validation');
	}
        
        public function index() {
            $user_id = $_SESSION["user"];
            $user = $this->doctrine->em->find('ORM\Dynasties2\Users', $user_id);
            
            $data['firstname'] = $user->getFirstName();
            $data['user_id'] = $user->getID();
            
            $this->load->library('session');
            $data['session_id'] = $this->session->userdata('session_id');
            
            $this->load->view('dynasties2/main_interface_view',$data);
            
            //$whichfamily = $user->getWhichFamily();
            
            // look in FAMILIES for whichUser = current user_id
            $has_family = $this->doctrine->em->getRepository('ORM\Dynasties2\Families')->findOneBy(array('whichUser' => $user_id));
                        
            //$this->load->library('session');
            // http://codeigniter.com/user_guide/libraries/sessions.html
            //print_r($this->session->all_userdata());
        
            
            if (is_null($has_family)) {
                // no such email address
                echo "<br />No such family.<br />"; 
                $this->load->view('dynasties2/create_family_view');
                
            } else {
                //echo "<br />Family data recovered.<br />"; 
                //$family = $this->doctrine->em->find('ORM\Dynasties2\Families', $whichfamily);
                //echo $has_family->getWhichUser();
                
                
                $this->load->view('dynasties2/toolbar_view');
               
                
                $this->load->model('dynasties2/display_family_model');
                $my_data['data'] = $this->display_family_model->show_all_living_family();
                $this->load->view('dynasties2/display_family_view', $my_data);
                
                
                $family = $_SESSION['active_family'];
                //echo $family;
                $query = $this->doctrine->em->createQuery("select u.id from ORM\Dynasties2\Characters u WHERE u.whichFamily = $family");
                $result = $query->getResult();
                if (empty($result)) {
                    
                    echo "Has no characters in family. Lets create them.";
                    $this->generate_family_members();
                    
                }
                
                
                //$familyname = $family->getfamilyname();
            }
            
        }   ////// end of function index
        ////////////////////////////////////////////////
        
        public function call_mail_creation_view() {
            $this->load->model('dynasties2/common_models');
            $familyids['data'] = $this->common_models->get_active_family_information();
            $this->load->view('dynasties2/mail_create_view', $familyids);
        }
        
        public function call_mail_reading_view() {
            
            $this->load->model('dynasties2/common_models');
            $mail_data['maildata'] = $this->common_models->get_my_unread_messages();
            $this->load->view('dynasties2/mail_reading_view', $mail_data);
		//print_r($mail_data);
            
            
            
        }
        
        
        
        
        public function mail_create_submit() {
            
            if ($this->_msg_validate() === FALSE) {
                $this->call_mail_creation_view();
                return;    
            }
            $this->load->model('dynasties2/common_models');
            $this->common_models->send_message();
            
            $this->call_mail_creation_view();
            
        }////// end of function mail_create_submit
        ////////////////////////////////////////////////
        
        
        
        private function _msg_validate() {
            
            $this->form_validation->set_rules('msgbody', 'msgbody',
                    'required|min_length[15]|trim|max_length[230]|xss_clean');
            $this->form_validation->set_rules('importance', 'importance',
                    'required|min_length[1]|trim|max_length[20]|xss_clean');
            $this->form_validation->set_rules('msgtype', 'msgtype',
                    'required|min_length[1]|trim|max_length[20]|xss_clean');
            $this->form_validation->set_rules('family_from', 'family_from',
                    'required|min_length[1]|trim|max_length[20]|xss_clean');
            $this->form_validation->set_rules('family_to', 'family_to',
                    'required|min_length[1]|trim|max_length[20]|xss_clean');
            
            return $this->form_validation->run();
            
        }
        
        
         public function test1() {
            
            //if (isset($_SESSION["user"])) {
             echo "This is function test1.</br>";
             echo $_SESSION["long_id"];
             
             $current_session = $this->doctrine->em->find('ORM\Dynasties2\Sessiontracker', $_SESSION["long_id"]);
             //$current_session = $current_session->setPagesVisited(+1);
             $current_count = $current_session->getPagesVisited();
             $current_count++;
             echo $current_count;
             $current_session->setPagesVisited($current_count);
             $this->doctrine->em->persist($current_session);
            $this->doctrine->em->flush();
            //} else {
                
                // deny, log, redirect
                
                
                //header( "Location: http://www.dixieandtheninjas.net/hellounderscoreworld/dynasties/start");
                //redirect('/dynasties2/start', 'location');
            //}
         } //////////// end of function test1
        ////////////////////////////////////////////////
         
         
         public function create_family(){
             
             //echo "</br> Function create_family.</br>";
             
             
             // do security checks if needed.  user authenticated?  which user?  already has family?
             $user_id = $_SESSION["user"];
             //$user = $this->doctrine->em->find('ORM\Dynasties2\Users', $user_id);
             //$whichfamily = $user->getWhichFamily();
             
             $has_family = $this->doctrine->em->getRepository('ORM\Dynasties2\Families')->findOneBy(array('whichUser' => $user_id));
             if (is_null($has_family)) {
                 
                 // no family for this user
                 //$this->load->view('dynasties2/create_family_view');
                 //echo "</br>Permission check passed.</br>";
                 
                 // execute code to create the family
                 if ($this->_family_name_validate() === FALSE) {
                     $this->index();
                     return;
                 }
                 
                 
                 $this->load->model('dynasties2/setup_data_model');
                 $this->setup_data_model->commit_new_family($user_id);
                 
                 echo "Completed function create_family! Now should run generate_family_members";
                 $this->generate_family_members();
                 
                
            }  // END of check to make sure that a family does not already exist.  all code in this function should go above this line.
             
         } ////////// end of function create_family
        ////////////////////////////////////////////////
         
         public function generate_male_name() {
            $query = $this->doctrine->em->createQuery("select max(u.id) from ORM\Dynasties2\Malenames u");
             $result = $query->getSingleResult();
             //echo $result2[1];
             $highval = $result[1];
             $random_name = rand(1,$highval);
             //echo $random_name;
             $name = $this->doctrine->em->find('ORM\Dynasties2\Malenames', $random_name);
             return $name->getName();
            
            
        }
        
        public function generate_female_name() {
            $query = $this->doctrine->em->createQuery("select max(u.id) from ORM\Dynasties2\Femalenames u");
             $result = $query->getSingleResult();
             //echo $result2[1];
             $highval = $result[1];
             $random_name = rand(1,$highval);
             //echo $random_name;
             $name = $this->doctrine->em->find('ORM\Dynasties2\Femalenames', $random_name);
             return $name->getName();
        }
        


        public function generate_family_members(){   /// change this back to private!!!
             echo "</br> Function (private) generate_family_members()  TEST</br>";
             //
             // need security check so that this function cannot be run without permission ... seems to be ok since making this a private function
            
             $family = $_SESSION['active_family'];
             //$has_characters = $this->doctrine->em->getRepository('ORM\Dynasties2\Characters')->findOneBy(array('whichFamily' => $family));
             //if (is_null($has_characters)) {
             $query = $this->doctrine->em->createQuery("select u.id from ORM\Dynasties2\Characters u WHERE u.whichFamily = $family");
             $result = $query->getResult();
             if (empty($result)) {  //// this line makes sure that there are not already existing family members.  all code should go beneath here.
             
             // need to know current turn
             $current_turn = '1';
             
             // determine birth turn for 'main' character,  should be no younger than 35 years(280), no older than 40 years (320)
             $age_rand = rand(280,320);
             $born_turn = $current_turn - $age_rand;
             //echo $born_turn;
             
             // great, his parents must have been married before this date.  lets figure 6 to 12 months before.
             $marriage_rand = rand(7,12);
             $parents_marriage_turn = $born_turn - $marriage_rand;
             // turn the parents were married ^^
             
             // how old are his parents?  Dad needs to be around 20 when married, give or take, and mom similar though both can vary some.
             // dad never younger than 19 and mom never younger than 18, dad never older than 24 mom never older than 24
             $dadage_atmarriage = rand(152,192);
             $momage_atmarriage = rand(144,192);

             $dad_born_turn = $parents_marriage_turn - $dadage_atmarriage;
             $mom_born_turn = $parents_marriage_turn - $momage_atmarriage;
             //echo $dad_born_turn;
             //echo $mom_born_turn;
             
             $dadage_years = ($current_turn - $dad_born_turn) / 8;
             //echo $dadage_years;
             
             /////////////
             ////// this is terrible random name code.  surely there is a way to do it better
             ////
             $father_name = $this->generate_male_name();
             /// end awful random name code
             
             $dad_died_turns_ago = rand(1,8);
             $dad_dead_turn = $current_turn - $dad_died_turns_ago;
             
             $character_data['name'] = $father_name;
             $character_data['whichfamily'] = $_SESSION['active_family'];
             $character_data['bornturn'] = $dad_born_turn;
             $character_data['deathturn'] = $dad_dead_turn;
             $character_data['marriedturn'] = $parents_marriage_turn;
             $character_data['marriedto'] = '0'; // need to get spouse ID
             $character_data['isfemale'] = '0';
             $character_data['fathersID'] = '0';
             $character_data['religion'] = '0';
             $character_data['successionorder'] = '0';
             $character_data['mothersID'] = '0';
             
             $this->load->model('dynasties2/setup_data_model');
             /// how do I get the returned results from this query right here????
             $dad_id = $this->setup_data_model->commit_new_character_to_db($character_data);
             /// answer... this ^^^
             
             //echo "new char ID is " . $dad_id;
             //echo $dad_id;
             echo "</br>Father created.</br>";
             //  ^^^^ dad created ^^^^
             
             /////////////
             ////// this is terrible random name code.  surely there is a way to do it better
             ////    probably needs to be a library for the time being
             ////
             $mother_name = $this->generate_female_name();
             /// end awful random name code
             
             $character_data['name'] = $mother_name;
             $character_data['whichfamily'] = $_SESSION['active_family'];
             $character_data['bornturn'] = $mom_born_turn;
             $character_data['deathturn'] = '0';  // we are assuming mom is still alive
             $character_data['marriedturn'] = $parents_marriage_turn;
             $character_data['marriedto'] = $dad_id; // need to get spouse ID
             $character_data['isfemale'] = '1';
             $character_data['fathersID'] = '0';
             $character_data['religion'] = '0';
             $character_data['successionorder'] = '0';
             $character_data['mothersID'] = '0';
             
             // unneccessary? $this->load->model('dynasties2/setup_data_model');
             $mom_id = $this->setup_data_model->commit_new_character_to_db($character_data);
             //echo $mom_id;  // need to use this to update husband's marriedto value
             $husband = $this->doctrine->em->find('ORM\Dynasties2\Characters', $dad_id);
             $husband->setMarriedTo($mom_id);
             $this->doctrine->em->persist($husband);
             $this->doctrine->em->flush();
             echo "</br>Mother created.</br>";
             //  ^^^^ mom created ^^^^
             
             ////////// begin create 'main character' /////////////
             
             /// note that this currently assumes that the main character is male!
             
             /// awful random name code
             $my_name = $this->generate_male_name();
             /// end awful random name code
             
             $character_data['name'] = $my_name;
             $character_data['whichfamily'] = $_SESSION['active_family'];
             $character_data['bornturn'] = $born_turn; /// generated way above
             $character_data['deathturn'] = '0';  
             $character_data['marriedturn'] = '0';  // not married?
             $character_data['marriedto'] = '0';  // not married?
             $character_data['isfemale'] = '0';
             $character_data['fathersID'] = $dad_id;
             $character_data['religion'] = '0';
             $character_data['successionorder'] = '1';   ///  <-- very important!
             $character_data['mothersID'] = $mom_id;
             
             $my_id = $this->setup_data_model->commit_new_character_to_db($character_data);
             
             /// need to create a family tree table to track mother as well..
             
             ////////////////// end creation of main character ////
             
             //////// create a wife!  //////
             
             $agerand = rand(264,304);
             $wife_born_turn = $current_turn - $agerand;  // turn that this person was born
             
             $marriagerand = rand(120,144);
             $married_turn = $current_turn - $marriagerand;
             
             /// awful random name code
             $wife_name = $this->generate_female_name();
             
             $character_data['name'] = $wife_name;
             $character_data['whichfamily'] = $_SESSION['active_family'];
             $character_data['bornturn'] = $wife_born_turn; /// generated way above
             $character_data['deathturn'] = '0';  
             $character_data['marriedturn'] = $married_turn;  // not married?
             $character_data['marriedto'] = $my_id;  // not married?
             $character_data['isfemale'] = '1';
             $character_data['fathersID'] = '0';
             $character_data['religion'] = '0';
             $character_data['successionorder'] = '0';
             $character_data['mothersID'] = '0';
             
             $wife_id = $this->setup_data_model->commit_new_character_to_db($character_data);
             
             $my_char = $this->doctrine->em->find('ORM\Dynasties2\Characters', $my_id);
             $my_char->setMarriedTo($wife_id);
             $my_char->setMarriedDate($married_turn);
             $this->doctrine->em->persist($my_char);
             $this->doctrine->em->flush();
             
             echo "</br>Primary character created.</br>";
             echo "</br>Wife created.</br>";
             
             ///////// end of create wife
             
             ////////// begin children creation code /////////////////
             // twins?
             // bastards?
             //
             /// create some children
             
             
        
                // how many?
                $hmany = rand(1,100);
                if ($hmany > '0' && $hmany < '31') {
                    // 3 living children
                    $children = '3';
                } else if ($hmany > '30' && $hmany < '51') {
                    // 4 living
                    $children = '4';
                } else if ($hmany > '50' && $hmany < '81') {
                    // 5 living
                    $children = '5';
                } else if ($hmany > '80' && $hmany < '101') {
                    // 6 living
                    $children = '6';
                }

                $crand = rand(7,24);

                $lastbirth = $married_turn + $crand;


                //$boys = '0';
                //$girls = '0';
                $succession = '2';
                while ($children > '0') {
                    $sex = rand(1,2);
                    if ($sex == '1') {
                        //$boys++;

                        /// awful random name code
                        $boy_name = $this->generate_male_name();

                        $bornafter = rand(7,24);
                        $birthday = $lastbirth + $bornafter;


                        if ($birthday <= $current_turn) {
                            
                            $character_data['name'] = $boy_name;
                            $character_data['whichfamily'] = $_SESSION['active_family'];
                            $character_data['bornturn'] = $birthday;
                            $character_data['deathturn'] = '0';  
                            $character_data['marriedturn'] = '0';  
                            $character_data['marriedto'] = '0'; 
                            $character_data['isfemale'] = '0';
                            $character_data['fathersID'] = $my_id;
                            $character_data['religion'] = '0';
                            $character_data['successionorder'] = $succession;
                            $character_data['mothersID'] = $wife_id;
                            
                            $this->setup_data_model->commit_new_character_to_db($character_data);
                            echo "</br>Child created.</br>";
                            $succession++;
                            /*
                                    /// makes sure that we don't have children with borndates later than the current turn
                                mysql_query("INSERT INTO characters (name, whichfamily, borndate, leaderskill, mgmtskill, spyskill, religion, location, succession, fathersID) 
                            VALUES ('$name', $famID, $birthday, '55', '55', '55', '1', '1', '$succession', '$mcharID')");
                                $charID = mysql_insert_id();
                                $succession++;

                                mysql_query("INSERT INTO familytree (charID, father, mother) 
                            VALUES ($charID, $mcharID, $wifeID)");

                                //echo "<br>Son created.</br>";
                             * 
                             */
                        } // no else!


                        } else {
                            //$girls++;

                            /// awful random name code
                            $girl_name = $this->generate_female_name();

                            $bornafter = rand(7,24);
                            $birthday = $lastbirth + $bornafter;

                            if ($birthday <= $current_turn) {
                                /// makes sure that we don't have children with borndates later than the current turn
                                
                                $character_data['name'] = $girl_name;
                                $character_data['whichfamily'] = $_SESSION['active_family'];
                                $character_data['bornturn'] = $birthday; 
                                $character_data['deathturn'] = '0';  
                                $character_data['marriedturn'] = '0'; 
                                $character_data['marriedto'] = '0'; 
                                $character_data['isfemale'] = '1';
                                $character_data['fathersID'] = $my_id;
                                $character_data['religion'] = '0';
                                $character_data['successionorder'] = '0';  // the system is sexist at the moment
                                $character_data['mothersID'] = $wife_id;
                                
                                $this->setup_data_model->commit_new_character_to_db($character_data);
                                  echo "</br>Child created.</br>";
                                $succession++;
                                
                                /*
                                    mysql_query("INSERT INTO characters (name, whichfamily, borndate, leaderskill, mgmtskill, spyskill, religion, location, isfemale, fathersID) 
                                VALUES ('$name', $famID, $birthday, '55', '55', '55', '1', '1', '1', '$mcharID')");
                                    $charID = mysql_insert_id();

                                    mysql_query("INSERT INTO familytree (charID, father, mother) 
                                VALUES ($charID, $famID, $wifeID)");
                                    //echo "<br>Daughter created.</br>";
                                 * 
                                 */
                            } 

                        } // no else!


                    $lastbirth = $birthday;
                    $children--;
                }
             //////////// end of children creation code
             
                
             
             
             } //// end of security check to make sure that family does not already have members generated. 
                /// all code in this function should go above this line.
             
         } ////////// end of function create_family_members
        ////////////////////////////////////////////////
        ////////////////////////////////////////////////
         
         private function _family_name_validate() {
             //echo "</br> Function (private) _family_name_validate.</br>";
         
             $this->form_validation->set_rules('family_name', 'family_name', 
                     'required|min_length[3]|max_length[16]|xss_clean|trim|callback_family_name_unique');
             
             return $this->form_validation->run();
             //echo "Testing line 1A";
             
         } ////// end of private function _family_name_validate
         ///////////////////////////////////////////////
         
         
         public function family_name_unique($str) {
             //echo "</br> Function  family_name_unique.</br>";
             
             $family_name_present = $this->doctrine->em->getRepository('ORM\Dynasties2\Families')->findOneBy(array('familyName' => $str));
             if (isset($family_name_present)) {
                        //echo "Testing line 1B";
                        $this->form_validation->set_message('family_name_unique', 'This family name is already in use');
                        return FALSE;
                } else
		{
			return TRUE;
		}
             
             
         }   ////// end of private function family_name_unique
         ///////////////////////////////////////////////
                 
         
         
         
    }    /////////////// END: class Main_interface extends CI_Controller 
    
}  //// END:  if (isset($_SESSION["user"]) && !empty($_SESSION["user"]))
else {
   // deny, log, redirect
    
    //$this->load->helper('url');
    //redirect('/dynasties2/start', 'location');
    
}


